<template>
  <q-select
    dense
    outlined
    :prefix="prefix"
    options-dense
    v-model="selected"
    class="q-my-sm"
    :options="options"
    emit-value
    map-options
    multiple
    style="min-width:210px;"
    ref="selectInput"
    @popup-show="hideSelectPop"
  >
    <q-menu ref="selMenu" fit>
      <tree-item :treeList="treeList" :multiple="multiple" :selected.sync="selected"
      @select="select" @selectMultiple="selectMultiple" />
    </q-menu>
  </q-select>
</template>

<script>
import TreeItem from './tree-item';

export default {
  components: { TreeItem },
  props: {
    prefix: {
      type: String,
      default: '',
    },
    value: [String, Array],
    treeList: Array,
  },
  data() {
    return {
      selected: [],
      multiple: false,
      options: [
      ],
      allOptions: [
      ],
    };
  },
  mounted() {
    // 先初始化所有选项
    this.initOptions(this.treeList);
    if (Array.isArray(this.value)) {
      this.selected = [...this.value];
      this.multiple = true;
      this.setOptions();
    } else if (this.value) {
      this.selected = [this.value];
      this.setOptions();
    } else {
      this.selected = [];
    }
  },
  methods: {
    initOptions(options) {
      options.forEach((opt) => {
        // 这里遍历出所有的选项
        this.allOptions.push({ label: opt.label, value: opt.value });
        if (opt.children) {
          this.initOptions(opt.children);
        }
      });
    },
    setOptions() {
      // 清空选项
      this.options = [];
      this.allOptions.forEach((option) => {
        if (this.selected.indexOf(option.value) !== -1) { this.options.push(option); }
      });
    },
    select(n) {
      this.selected = [n];
      this.setOptions();
      this.$refs.selMenu.hide();
      this.$emit('input', n);
    },
    hideSelectPop() {
      this.$refs.selectInput.hidePopup();
    },
    selectMultiple(selNode) {
      this.selected = selNode;
      this.setOptions();
      this.$emit('input', selNode);
    },
  },
  created() { },
};
</script>
<style lang="stylus"></style>
